/*

//
//  MapViewController.m
//  Comic
//
//  Created by Ryan on 16/3/19.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "MapViewController.h"
#import "MapCollectionViewCell.h"
#define APIKEY @"7d9a40a80b76d57e5bb797316bf62efe"

@interface MapViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate,MAMapViewDelegate,AMapSearchDelegate>

@property (nonatomic,strong)MAMapView *mapView;

@property (nonatomic,strong)AMapSearchAPI *search;

@property (nonatomic,strong)UISearchBar *searchBar;

@property (nonatomic,strong)UIButton *map_Button;
@property (nonatomic,strong)UIButton *road_Button;

@property (nonatomic,assign)BOOL isMap;
@property (nonatomic,assign)BOOL isRoad;
@property (nonatomic,assign) BOOL isExpanded;


@property (nonatomic,strong)UIView *maskView;
@property (nonatomic,strong)UICollectionView *map_collectionView;
@property (nonatomic,strong)UICollectionViewFlowLayout *flowLayout;

@property (nonatomic,strong)UIView *backView;


@property (nonatomic,copy)NSString *_title;
@property (nonatomic,copy)NSString *subtitle;

@property (nonatomic,assign)CLLocationCoordinate2D coordinate;

@property (nonatomic,copy)NSString *keywords;

@property (nonatomic,strong)NSArray *city;






@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
   
    //配置用户Key
    [MAMapServices sharedServices].apiKey = APIKEY;
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _mapView.delegate = self;
    _mapView.userInteractionEnabled = YES;
    
    
    [self.view addSubview:_mapView];
    
    //配置用户Key
    [AMapSearchServices sharedServices].apiKey = APIKEY;

    
    
    
    //后台执行
    _mapView.pausesLocationUpdatesAutomatically = NO;
    
    _mapView.allowsBackgroundLocationUpdates = YES;
    
   
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    [self searchData];
    
    
    [self createView];
    
    [self createFrame];


}

- (void)viewDidAppear:(BOOL)animated{
    

    

    
    //定位图层显示模式

    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;

    [_mapView setZoomLevel:16.1 animated:YES];
    
    //大头针标注
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    pointAnnotation.coordinate = self.coordinate;
    pointAnnotation.title = self._title;
    pointAnnotation.subtitle = self.subtitle;
    
    [_mapView addAnnotation:pointAnnotation];


}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    
    self.navigationController.navigationBarHidden = YES;



}

- (void)viewDidDisappear:(BOOL)animated{

    self.navigationController.navigationBarHidden = NO;

}

#pragma mark 创建视图


- (void)createView{

    self.searchBar = [UISearchBar new];
    
    self.map_Button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self.map_Button addTarget:self action:@selector(map_Button:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.road_Button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self.road_Button addTarget:self action:@selector(road_Button:) forControlEvents:UIControlEventTouchUpInside];
    
    self.maskView = [UIView new];
    
    self.maskView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];
    
    self.mapView.userInteractionEnabled = YES;
    
    self.maskView.hidden = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
    
    [self.maskView addGestureRecognizer:tap];
    
    
    
    
    self.backView = [UIView new];
    
    self.backView.backgroundColor = [UIColor whiteColor];
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    
//    self.flowLayout.itemSize = CGSizeMake(1,1);
    self.flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-50)/3.0, (SCREEN_WIDTH-50)/4.2);

    self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
 
    
    self.map_collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 135, 3, 3) collectionViewLayout:_flowLayout];
    
    self.map_collectionView.backgroundColor =[UIColor whiteColor];
    
    self.map_collectionView.layer.cornerRadius = 4;
    
    self.map_collectionView.scrollEnabled = NO;
    
    [self.map_collectionView registerClass:[MapCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MapCollectionViewCell class])];
    
    self.map_collectionView.delegate = self;
    
    self.map_collectionView.dataSource = self;

    [self.map_collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    
    
}

- (void)createFrame{

    
    
    [self.view addSubview:self.searchBar];

    self.searchBar.placeholder = @"查找地点,公交,地铁";
    
    
    [self.view addSubview:self.road_Button];

    [self.view addSubview:self.maskView];
    
    [self.view addSubview:self.backView];
    
    [self.view addSubview:self.map_Button];
    
    [self.map_Button setTitle:@"地图" forState:UIControlStateNormal];
    self.map_Button.backgroundColor = [UIColor whiteColor];
    self.map_Button.layer.cornerRadius = 3;
    self.map_Button.layer.borderWidth = 1;
    self.map_Button.layer.borderColor = [UIColor grayColor].CGColor;
    
    
    [self.road_Button setTitle:@"路况" forState:UIControlStateNormal];
    self.road_Button.backgroundColor = [UIColor whiteColor];
    self.road_Button.layer.cornerRadius = 3;
    self.road_Button.layer.borderWidth = 1;
    self.road_Button.layer.borderColor = [UIColor grayColor].CGColor;
    
    
    [self.view addSubview:self.map_collectionView];
    
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_equalTo(10);
        
        make.right.mas_equalTo(-10);
        
        make.top.mas_equalTo(40);
        
        make.height.mas_equalTo(45);
        
        
    }];
    [self.map_Button mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(self.searchBar.mas_bottom).offset(10);
        make.right.mas_equalTo(-10);
        make.width.height.mas_equalTo(40);
        
        
    }];
    
    [self.road_Button mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(self.map_Button.mas_bottom).offset(10);
        make.right.mas_equalTo(-10);
        make.width.height.mas_equalTo(40);

        
        
    }];
    
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.mas_equalTo(0);
        
        
    }];
    

    

}




//当位置更新时，会进定位回调，通过回调函数，能获取到定位点的经纬度坐标，示例代码如下：

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        
        self.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
        
    }
}


- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MAAnnotationView *view = views[0];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.fillColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:0.3];
        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
        pre.image = [UIImage imageNamed:@"location.png"];
        pre.lineWidth = 1;
//        pre.lineDashPattern = @[@6, @3];
        
        [self.mapView updateUserLocationRepresentation:pre];
        
        view.calloutOffset = CGPointMake(0, 0);
    } 
}



#pragma mark 搜索


- (void)searchData{

    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    

    
//    //构造AMapInputTipsSearchRequest对象，设置请求参数
//    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
//    tipsRequest.keywords = @"肯德基";
//    tipsRequest.city = @"大连";
//    
//    //发起输入提示搜索
//    [_search AMapInputTipsSearch: tipsRequest];
//    
    
    
    
    
    
    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:_coordinate.latitude longitude:_coordinate.longitude];
    request.keywords = @"小吴家家";
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
    // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
    request.types = @"餐饮服务|生活服务";
    request.sortrule = 0;
    request.requireExtension = YES;
    
    //发起周边搜索
    [_search AMapPOIAroundSearch: request];

}

//实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0)
    {
        return;
    }
    
    //通过 AMapPOISearchResponse 对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %ld",response.count];
    NSString *strSuggestion = [NSString stringWithFormat:@"Suggestion: %@", response.suggestion];
    NSString *strPoi = @"";
    for (AMapPOI *p in response.pois) {
        strPoi = [NSString stringWithFormat:@"%@\nPOI: %@", strPoi, p.description];
    }
    NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n %@", strCount, strSuggestion, strPoi];
    NSLog(@"Place: %@", result);
}


#pragma mark 大头针


- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
    
    
    
    
}


#pragma mark 按钮点击方法

- (void)map_Button:(UIButton *)button{

    self.isMap = !self.isMap;
    
    if (self.isMap) {
        
        self.maskView.hidden = NO;
        
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.map_collectionView.frame = CGRectMake(10, 136,SCREEN_WIDTH - 20, (SCREEN_WIDTH-50)/4.2 + 10);
            
            
//            self.flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-50)/3.0, (SCREEN_WIDTH-50)/4.2);

        }];
        
        

        
    }else{
            self.maskView.hidden = YES;
        
        [UIView animateWithDuration:0.5 animations:^{
//            self.flowLayout.itemSize = CGSizeMake(1,1);

            self.map_collectionView.frame = CGRectMake(SCREEN_WIDTH, 136, 3, 3);
            
        }];
        
        
        
    }
    
}







- (void)road_Button:(UIButton *)button{
    
    if (self.isRoad) {
        NSLog(@"1");
    }else{
        NSLog(@"2");
    }
    
    self.isRoad = !self.isRoad;

    
}

#pragma mark collectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    return 3;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MapCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([MapCollectionViewCell class]) forIndexPath:indexPath];
    
    switch (indexPath.row) {
        case 0:
            
            cell.type_Label.text = @"标准地图";
            
            NSLog(@"1");
            break;
        case 1:
            
            cell.type_Label.text = @"卫星地图";
            
            break;
        case 2:
            
            cell.type_Label.text = @"公交地图";
            
            break;
            
        default:
            break;
    }
    
    cell.backgroundColor = [UIColor redColor];
    cell.mask_View.backgroundColor = [UIColor grayColor];
    cell.type_Label.highlightedTextColor = [UIColor blueColor];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    switch (indexPath.row) {
        case 0:{
            
            _mapView.mapType = MAMapTypeStandard;
            self.isMap = !self.isMap;

            
            self.maskView.hidden = YES;
            
            [UIView animateWithDuration:0.5 animations:^{
                
                self.map_collectionView.frame = CGRectMake(SCREEN_WIDTH, 136, 3, 3);
                
            }];
            
        }
            break;
        case 1:
        {   _mapView.mapType = MAMapTypeSatellite;
            self.isMap = !self.isMap;
            
            self.maskView.hidden = YES;
            
            [UIView animateWithDuration:0.5 animations:^{
                
                self.map_collectionView.frame = CGRectMake(SCREEN_WIDTH, 136, 3, 3);
                
            }];
            

        }
            break;
        case 2:
            
            
            break;
            
        default:
            break;
    }
    
    
    
    
}


#pragma mark 轻点

- (void)tapClick:(UITapGestureRecognizer *)tap{
    
    self.isMap = !self.isMap;
    
    self.maskView.hidden = YES;
    
    [UIView animateWithDuration:0.5 animations:^{
        //            self.flowLayout.itemSize = CGSizeMake(1,1);
        
        self.map_collectionView.frame = CGRectMake(SCREEN_WIDTH, 136, 3, 3);
        
    }];
    


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//@end